package com.whiteape.book.core.engine;

import com.jayway.jsonpath.JsonPath;
import com.whiteape.book.utils.StringUtils;

import net.minidev.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

/**
 * json path引擎
 */
public class JsonPathEngine {

    public static String getString(String jsonStr, String rule) {
        try {
            if (StringUtils.isEmpty(rule)) {
                return "";
            }
            Object obj = JsonPath.read(jsonStr, rule);
            if (obj instanceof JSONArray) {
                //TODO 如果不小心获取多个了，默认取第一个?
                if (((JSONArray) obj).size() > 0) {
                    return ((JSONArray) obj).toJSONString();
                } else {
                    return "[]";
                }
            }
            return JsonPath.read(jsonStr, rule).toString();
        }catch (Exception e) {
//            e.printStackTrace();
            return "";
        }
    }

    public static List<String> getStringList(String jsonStr, String rule) {
        if (StringUtils.isEmpty(rule)) {
            return new ArrayList<>();
        }
        return JsonPath.read(jsonStr, rule);
    }

    public static List getElementList(String jsonStr, String rule) {
        if (StringUtils.isEmpty(rule)) {
            return new ArrayList<>();
        }
        return JsonPath.read(jsonStr, rule);

    }

}
